<template>
    <!-- 集采汇总编辑页 -->
    <div class="e-form">
        <BillTop  @cancel="handleClose"></BillTop>
        <div class="tabs warningTabs">
            <el-tabs tab-position="left" v-model="tabsName" @tab-click="onChangeTab">
                <!-- 基本信息 -->
                <el-tab-pane label="基本信息" name="baseInfo" :disabled="clickTabFlag"></el-tab-pane>
                <el-tab-pane label="汇总明细" name="planDetail" :disabled="clickTabFlag"></el-tab-pane>

                <el-tab-pane label="附件信息" name="accessory" :disabled="clickTabFlag"></el-tab-pane>
                <el-tab-pane label="审核历史" name="auditHistory" :disabled="clickTabFlag"></el-tab-pane>

                <div>
                    <!-- 基本信息 -->
                    <div id="baseInfoCon" class="con">
                        <div class="e-form">
                            <div class="tabs">
                                <div class="tabs-title" id="baseInfo">
                                    基本信息
                                </div>
                                <div style="width: 100%" class="form">
                                    <el-form :model="basicForm" :rules="rules" ref="basicForm" class="demo-ruleForm"
                                        label-width="150px">
                                        <el-row>
                                            <el-col :span="12">
                                                <el-form-item label="计划编号：">
                                                    <span>{{
                                                            basicForm.billNo
                                                    }}</span>
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item label="单据机构：">
                                                    <span>{{
                                                            basicForm.orgName
                                                    }}</span>
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                        <el-row>
                                            <el-col :span="12">
                                                <el-form-item label="计划金额：">
                                                    <span>{{
                                                            basicForm.amount
                                                    }}</span>
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item label="汇总日期：" prop="summaryDate">
                                                    <el-date-picker type="date" placeholder="选择日期" v-model="
                                                        basicForm.summaryDate
                                                    "></el-date-picker>
                                                </el-form-item>
                                            </el-col>
                                        </el-row>

                                        <el-row>
                                            <el-col :span="12">
                                                <el-form-item label="币种：" prop="currencyId">
                                                    <el-select v-model="
                                                        basicForm.currencyId
                                                    " placeholder="请选择" @change="currencyChange">
                                                        <el-option v-for="item in currencyForm" :key="item.value"
                                                            :label="item.label" :value="item.value">
                                                        </el-option>
                                                    </el-select>
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item label="填报人：">
                                                    <span>{{
                                                            basicForm.preparer
                                                    }}</span>
                                                </el-form-item>
                                            </el-col>
                                        </el-row>

                                        <el-row>
                                            <el-col :span="12">
                                                <el-form-item label="本位币：">
                                                    <span>{{
                                                            basicForm.baseCurName
                                                    }}</span>
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item label="本位币汇率：">
                                                    <el-input v-model="
                                                        basicForm.baseCurRate
                                                    "></el-input>
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                        <el-row>
                                            <el-col :span="12">
                                                <el-form-item label="人民币汇率：">
                                                    <span>{{
                                                            basicForm.rmbRate
                                                    }}</span>
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item label="状态：">
                                                    <span>{{
                                                            statusLable(
                                                                basicForm.state
                                                            )
                                                    }}</span>
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                        <el-row>
                                            <el-col :span="24">
                                                <el-form-item label="备注：">
                                                    <el-input type="textarea" v-model="
                                                        basicForm.remarks
                                                    " autocomplete="off"></el-input>
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                    </el-form>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- 汇总明细 -->
                    <div id="planDetailCon" class="con">
                        <div class="tabs-title" id="planDetail">汇总明细</div>
                        <el-tabs :class="'childTab ' + childTabClass" tab-position="left" v-model="tabsNameChild"
                            @tab-click="onChangeTab">
                            <el-tab-pane label="按申报机构汇总" name="materialDetails" :disabled="clickTabFlag"></el-tab-pane>
                            <el-tab-pane label="物资汇总" name="technicalParameter" :disabled="clickTabFlag"></el-tab-pane>
                            <div>
                                <div id="planDetailCon">
                                    <div class="tabs-title" id="materialDetails">
                                        按申报机构汇总
                                    </div>
                                    <div class="e-table">
                                        <applicationUnit :billId="billId" @basicFormAmount="basicFormAmount"/>

                                        <div class="errorMsg" v-if="errorMsg.length > 0">
                                            <span v-for="(
                                                    item, index
                                                ) in errorMsg" :key="index">
                                                {{ item }}
                                            </span>
                                        </div>
                                    </div>
                                </div>
                                <div id="planDetailCon">
                                    <div class="tabs-title" id="technicalParameter">
                                        物资汇总
                                    </div>
                                    <div class="e-table">
                                        <materialSummary :billId="billId" />

                                    </div>
                                </div>
                            </div>
                        </el-tabs>
                    </div>

                    <!-- 附件信息 -->
                    <div id="accessoryCon" class="con">
                        <div class="tabs-title" id="accessory">附件信息</div>
                        <attach-comp :relationId="attachId" bucketName="turnover" />
                    </div>
                    <!-- 审核历史 -->
                    <div id="auditHistoryCon" class="con">
                        <div class="tabs-title" id="auditHistory">审核历史</div>
                        <div class="e-table">
                            <div class="e-table">
                                <ComAuditHistoryIndex :billType="6087" ref="AuditHistoryRef" />
                            </div>
                        </div>
                    </div>
                </div>
            </el-tabs>
        </div>
        <div id="seat" :style="{ height: seatHeight + 'px' }"></div>
        <div class="buttons">
            <span class="tip"><span style="color: red; margin-right: 0">*</span>为必填项</span>
            <ComExaButtons :auditState="auditState" :state="basicForm.state" @exas="exas"
                :founderId="basicForm.founderId" />
            <!-- <el-button
                type="primary"
                class="btn-blue"
                @click="submitCommit"
                size="small"
                >保存并提交</el-button
            >
            <el-button
                type="primary"
                class="btn-blue"
                @click="submit"
                size="small"
                >保存</el-button
            >
            <el-button
                slot="reference"
                type="primary"
                class="btn-delete"
                @click="clickDel"
                v-if="auditState.canModify"
                size="small"
                >删除</el-button
            > -->
            <el-button size="small" @click="handleClose">取消</el-button>
        </div>
    </div>
</template>

<script>
import '@/utils/jquery.scrollTo.min'
import { mapMutations, mapState } from 'vuex'
import { showSuccessPop, getUuid } from '@/utils/common'
import AttachComp from '@/components/common/attachIndex'
import planRequest from '@/api/turnover/plan.js'
import { getRmbRate } from '@/api/equip/common.js'
import ComExaButtons from '@/components/common/exaButtons'
import { exas, saveAll, submitCommit } from '@/pages/revolveMaterialManage/common/revolveCom.js'
import auditRequest from '@/api/turnover/audit.js'
import ComAuditHistoryIndex from '@/pages/revolveMaterialManage/components/auditHistory/auditHistoryIndex'
// import historyUpdateTable from '@/components/common/historyUpdateTable'

import applicationUnit from './applicationUnit'
import materialSummary from './materialSummary'
export default {
    components: {
        AttachComp,
        ComAuditHistoryIndex,
        // historyUpdateTable,
        applicationUnit,
        materialSummary, //物资汇总
        ComExaButtons
    },
    data () {
        return {
            ress: '',
            auditState: {},
            auditParams: {
                billId: this.$route.query.billid,
                billType: 6087,
                freeNextUnitIndex: 0,
                freeNextUser: '',
                isPass: true,
                isShareInAudit: true,
                opinion: ''
            },
            tabsName: 'baseInfo',
            userName: '',
            clickId: 'baseInfo',
            tabsNameChild: '',
            childTabClass: '',
            form: {
                name: '',
                region: '',
                date1: '',
                date2: '',
                delivery: false,
                type: [],
                resource: '',
                desc: ''
            },

            OrgtableData: [], //申报机构数据
            OrgSonTableData: [], //申报机构子列表
            materialsTableData: [], //物资汇总数据
            auditHistoryList: [], //审核历史
            planSelect: [], //申报机构表格明细选择项
            value: '',
            textarea: '',
            formData: {},
            screenWidth: 0,
            screenHeight: 0,
            lastConHeight: 0,
            MouseEnterId: 0,
            clickTabFlag: false, // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            //基本信息表单数据
            basicForm: {
                amount: 0,
                baseCurAmount: 0,
                baseCurId: '',
                baseCurName: '',
                baseCurRate: 0,
                billId: '',
                billNo: '',
                currency: '',
                currencyId: '',
                nullifyCreated: '',
                nullifyCreator: '',
                nullifyCreatorId: '',
                nullifyDescription: '',
                nullifyReason: '',
                orgId: '',
                orgName: '',
                preparer: '',
                preparerId: '',
                remarks: '',
                rmbAmount: 0,
                rmbId: '',
                rmbName: '',
                rmbRate: 0,
                sourceType: 0,
                state: 0,
                summaryDate: '',
                workId: ''
            },
            objFlag: {
                flag5: false
            },
            orgId: '', //机构id
            orgName: '', //机构名称
            billId: '',
            isSkip: false, //是否跳转
            show: true, //申报机构子列表
            dtlIds: '', //
            //验证
            rules: {
                summaryDate: [
                    {
                        required: true,
                        message: '请输入汇总日期',
                        trigger: 'blur'
                    }
                ],
                currencyId: [
                    { required: true, message: '请选择币种', trigger: 'chenge' }
                ]
            },
            showBaseCurName: false,
            materialsNameData: [], //机构汇总表
            createHistoryData: [], //明细修改历史列表
            errorMsg: [],
            isErrorMsg: true, //是否提醒错误信息
            onlyID: '', //判断选择那行的唯一id
            procurementMethod: [{
                value: 0,
                label: '邀请招标'
            }, {
                value: 1,
                label: '公开招标'
            }, {
                value: 2,
                label: '询价'
            }, {
                value: 3,
                label: '竞争性谈判'
            }, {
                value: 4,
                label: '单一性来源'
            },
            {
                value: 5,
                label: '甲控（业主招标）'
            }],
            annualDemandPlanBillIdArr: [], //申年度计划IDs
            itemObj: {}, //物资汇总去重
            test: []
        }
    },
    created () {
        let data = JSON.parse(localStorage.getItem('vuex'))
        this.orgId = data.userInfo.orgInfo.orgId
        this.orgName = data.userInfo.orgInfo.orgName
        this.userId = localStorage.getItem('userId')
        this.basicForm.operator = localStorage.getItem('userName')
        this.billId = this.$route.query.billid

        this.initData()
    },
    watch: {
        //给错误标签加上提醒
        errorList: newData => {
            const tabs = document.querySelectorAll('.el-tabs__item')
            tabs.forEach(DOM => {
                const { childNodes } = DOM
                if (childNodes.length > 1) {
                    DOM.removeChild(childNodes[1])
                }
            })
            newData.forEach(item => {
                const itemDom = document.querySelector(`#tab-${item}`)
                var element = document.createElement('i')
                element.className = 'el-icon-warning-outline warning'
                itemDom.appendChild(element)
            })
        },
    },
    methods: {
        ...mapMutations([
            'setPopConfirm',
            'setSelectedInfo',
            'setHistoryTableData'
        ]),

        initData () {
            this.getCurrentUnitInfo()
            this.getTurnoverCentralizedPurchaseSummaryGetAgencyListByBillId()
            this.getBasicData()
            this.getTurnoverCentralizedPurchaseSummaryGetSummarySetting() //回去物资汇总明细
        },
        //跳转到明细
        scorllDtl () {
            if (this.$route.query.name) {
                setTimeout(() => {
                    //因为dom异步加载，通过轮询找到渲染后的dom，获取高度
                    let obj = {
                        name: this.$route.query.name
                    }
                    this.tabsName = this.$route.query.name
                    this.onChangeTab(obj)
                }, 200)
            }
        },

        //获取按钮状态
        getCurrentUnitInfo () {
            auditRequest.getCurrentUnitInfo(this.auditParams).then(res => {
                this.auditState = res
            })
        },
        //根据周材集采汇总id查询申报机构
        getTurnoverCentralizedPurchaseSummaryGetAgencyListByBillId () {
            planRequest
                .turnoverCentralizedPurchaseSummaryGetAgencyListByBillId(
                    this.billId
                )
                .then(res => {
                    this.OrgtableData = res
                    // this.rollUp(res)
                })
        },

        //根据周材集采汇总id查询申报机构
        getTurnoverCentralizedPurchaseSummaryGetSummarySetting () {
            planRequest
                .turnoverCentralizedPurchaseSummaryGetSummarySetting(
                    this.billId
                )
                .then(res => {
                    console.log(res, '当前打印')
                    // this.OrgtableData = res
                    // this.notSetData = JSON.parse(JSON.stringify(res)) //没去重之前的数据
                    // //去重
                    let children = []
                    res.forEach(item => {
                        item.children.forEach(a => {
                            children.push(a)
                        })
                    })
                    var result = []
                    var obj = {}
                    for (var i = 0; i < children.length; i++) {
                        if (children[i].materialId in obj) {
                            // 相同时肯定不push
                            if (
                                obj[children[i].materialId] !==
                                children[i].texture
                            ) {
                                // 不相同时，判断是否是 '' 和 null，如果是，则表示重复
                                if (
                                    !(
                                        !obj[children[i].materialId] &&
                                        !children[i].texture
                                    )
                                ) {
                                    // 当都不是 '' 和 null 时，才表示不重复，此时才push
                                    result.push(children[i])
                                }
                            }
                        } else {
                            obj[children[i].materialId] = children[i].texture
                            result.push(children[i])
                        }
                        // obj[children[i].amount] = 1
                    }
                    res.forEach(item => {
                        item.uuid = getUuid()

                        item.materialClassName = item.topClassName
                        item.children = result
                        item.children.forEach(v => {
                            v.uuid = getUuid()
                            v.parentId = item.uuid
                            v.amount = null
                        })
                    })
                    console.log(result, 'datadata')
                    this.materialsTableData = res
                })
        },
        //币种切换
        currencyChange (val) {
            this.basicForm.currency = this.currencyForm.find(
                x => x.value === val
            ).label //币种
            if (this.basicForm.currency === '人民币') {
                this.basicForm.rmbRate = 1
            } else {
                getRmbRate({
                    //获取机构下某币种的人民币汇率
                    currency: val,
                    orgId: this.userInfo.orgInfo.orgId
                })
                    .then(res => {
                        this.basicForm.rmbRate = res.rate
                    })
                    .catch(() => { })
            }
            if (this.basicForm.currencyId === this.basicForm.baseCurId) {
                //币种=本位币
                this.basicForm.baseCurRate = 1
                this.showBaseCurName = false
            } else {
                this.basicForm.baseCurRate = null
                this.showBaseCurName = true
            }
        },
        // 获取金额汇总
        basicFormAmount (value) {
            this.basicForm.amount = value
        },
        //点击图标的时候 获取历史记录
        clickIcon (dtlId, column) {
            this.setHistoryTableData([])
            alert(dtlId)
            planRequest
                .turnoverAnnualDemandPlanGetHistoryList(
                    dtlId,
                    column,
                    this.auditParams.billType
                )
                .then(res => {
                    this.historyTableData = res
                    this.setHistoryTableData(res)
                })
                .catch(e => {
                    alert(e.message)
                })
        },
        // 编辑的时候造历史修改数据结构
        createHistory (row, e) {
            if (row.dtlId) {
                this.createHistoryData.push({
                    historyId: '',
                    modifedName: '',
                    modifiedDate: '',
                    modifiedId: '',
                    opinion: '',
                    sourceId: row.dtlId,
                    sourceValue: 0,
                    updateColumn: e, //修改字段
                    updatedValue: row[e] //修改后的值
                })
            }
        },
        /**
         * 下边几个按钮
         */
        //更新基本信息
        updateBaseInfo () {
            return new Promise((resolve, reject) => {
                this.$refs.basicForm.validate(valid => {
                    if (valid) {
                        planRequest
                            .turnoverCentralizedPurchaseSummaryUpdate(
                                this.basicForm
                            )
                            .then(() => {
                                resolve()
                            })
                            .catch(err => {
                                reject(err)
                                this.setError('baseInfo')
                                this.scorllError()
                            })
                    } else {
                        reject()
                        this.setError('baseInfo')
                        this.scorllError()
                        return false
                    }
                })
            })
        },
        //保存申报机构及其明细
        updateDetailInfo () {

            return new Promise((resolve, reject) => {
                const data = JSON.parse(JSON.stringify(this.unitTableData))
                this.verifyTable().then(() => {
                    planRequest.turnoverCentralizedPurchaseSummaryUpdateDtlList(data)
                        .then(() => {
                            resolve()
                        })
                        .catch(err => {
                            reject(err)
                            this.setError('planDetail')
                            this.scorllError()
                        })
                }).catch(err => {
                    this.setError('planDetail')
                    reject(err)
                    this.scorllError()
                })
            })
        },
        //更新物资汇总
        updateMaterialsDetailInfo () {
            return new Promise((resolve, reject) => {
                planRequest.turnoverCentralizedPurchaseSummarySaveSummarySetting(this.materialsSummaryTableDataVuex)
                    .then(() => {
                        resolve()
                    })
                    .catch(err => {
                        reject(err)
                        this.setError('technicalParameter')
                        this.scorllError()
                    })
            })
        },
        async exas (arg) {
            const requestFn = () => {
                return []
            }
            exas(arg, this, requestFn)
        },
        //保存全部数据
        saveAll () {
            const requestFn = ()=>{
                return [
                    this.updateBaseInfo(),
                    this.updateDetailInfo(),
                    this.updateMaterialsDetailInfo(),

                ]
            }
            saveAll(this, requestFn)
        },
        submitCommit () {
            const requestFn = ()=>{
                return [
                    this.updateBaseInfo(),
                    this.updateDetailInfo(),
                    this.updateMaterialsDetailInfo(),
                ]
            }
            submitCommit(this, requestFn)
        },
        //计划明细非空验证
        verifyTable () {
            return new Promise((resolve, reject) => {
                this.errorMsg = []
                if (this.OrgtableData.length > 0) {
                    this.OrgtableData.forEach((n, index) => {
                        if (n.dtls) {
                            n.dtls.forEach(v => {
                                v.children.forEach(item => {
                                    if (item.changeType !== -1) {
                                        if (item.approvalQuantity === '' || item.approvalQuantity === null) {
                                            let str = `请填写第 ${index + 1} 行的核准数量`
                                            this.errorMsg.push(str)
                                        }
                                        if (item.approvalPrice === '' || item.approvalPrice === null) {
                                            let str = `请填写第 ${index + 1} 行的核准单价`
                                            this.errorMsg.push(str)
                                        }
                                    }
                                })
                            })
                        }
                    })
                }
                if (this.errorMsg.length > 0) {
                    reject()
                } else {
                    resolve()
                }
            })
        },

        //选择行颜色
        rowStyle ({ row }) {
            if (!this.onlyID) return
            if (this.onlyID === row.annualDemandPlanBillId) {
                return {
                    'background-color': 'rgb(179,210,238)!important'
                }
            }
        },

        //获取集采汇总id获取基本信息
        getBasicData () {
            planRequest
                .turnoverCentralizedPurchaseSummaryFindById(this.billId)
                .then(res => {
                    this.basicForm = res
                })
        },
        //删除提示框
        clickDel () {
            this.clientPop(
                'info',
                '确定要删除吗？删除的数据可以在【回收站】还原或彻底删除。',
                this.delData
            )
        },
        //根据集采汇总id删除单据
        delData () {
            planRequest
                .turnoverCentralizedPurchaseSummaryDelete(this.billId)
                .then(res => {
                    if (res.code == 200) {
                        showSuccessPop('删除成功！')
                        this.isSkip = true
                    }
                    this.$router.push('/revolveCollectList')
                })
        },
        handleFullScreen () {
            this.fullscreen = !this.fullscreen
        },
        //查询附件信息
        getAttach () {
            this.objFlag.flag5 = true
        },
        //申报机构删除逻辑
        tableRowClassName ({ row }) {
            if (row.changeType === -1) {
                return 'warning-row'
            }
            return ''
        },
        //获取用户在 汇总明细-申报机构汇总 表格的已选择项
        planTableSelect (selection) {
            this.planSelect = selection
        },
        //取消
        handleClose () {
            this.dialogVisible = false
            this.$router.replace('./revolveCollectList')
        },
        onChangeTab (e) {
            const height  = $('#' + e.name).offset().top
            $.scrollTo(height - this.topHeight, 500)
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            this.clickTabFlag = true
            // 动画结束后，恢复状态
            setTimeout(() => {
                this.clickTabFlag = false
            }, 600)
        },
        // 获取最后一个内容区域的高度，计算底部空白
        getLastConHeight () {
            let si = setInterval(() => {
                // 因为dom异步加载，通过轮询找到渲染后的dom，获取高度
                if (document.getElementById('evaluateCon')) {
                    const lastConHeight =
                        document.getElementById('evaluateCon').offsetHeight
                    console.log('lastConHeight: ', lastConHeight)
                    this.lastConHeight = lastConHeight
                    console.log('this.lastConHeight', this.lastConHeight)
                    clearInterval(si)
                    si = null
                }
            }, 100)
        },
        //设置错误标签
        setError (name) {
            if (!this.errorList.find(x => x === name)) {
                this.errorList.push(name)
            }
        },
        //跳转到第一个错误标签
        scorllError () {
            let num = this.tabArr.length
            this.errorList.forEach(item => {
                let index = this.tabArr.findIndex(x => x === item)
                num = index < num ? index : num
            })
            const obj = { name: this.tabArr[num] }
            this.tabsName = this.tabArr[num]
            this.onChangeTab(obj)
        },
        cellClsNm ({ column }) {
            if (column.label === '') {
                return 'fixed-left'
            }
        }
    },
    computed: {
        ...mapState({
            options: state => state.contract.ctClassify,
            popConfirm: 'popConfirm',
            popStatus: 'popStatus',
            userInfo: state => state.userInfo,
            currencyForm: state => state.equip.equipData.currencyForm, //币种
            planBillIdArr: state => state.turnover.planBillIdArr, //申报单位的billId
            unitTableData: state => state.turnover.unitTableData, //申报单位以及明细数据
            materialsSummaryTableDataVuex: state => state.turnover.materialsSummaryTableData, //表格汇总数据
        }),

        judgeRoute () {
            if (this.$route.path.includes('Add')) {
                return false
            }
            return true
        },
        // 填补底部空白，以使高度够滚动
        seatHeight () {
            return this.screenHeight - 72 - this.lastConHeight
        },
        attachId () {
            return this.billId
        },
        statusLable () {
            return param => {
                const state = this.$store.state.equip.equipData.state
                const obj = state.find(x => x.value == param)

                if (obj !== undefined) {
                    return obj.label
                }
            }
        }
    },

    mounted () {
        // 获取最后一个内容区域的高度，计算底部空白
        this.getLastConHeight()

        // 保存所有tabName
        const arr = [
            'baseInfo',
            ['planDetail', 'materialDetails', 'technicalParameter'],
            'accessory',
            'auditHistory'
        ]
        this.tabArr = arr
        let $idsTop = []
        window.addEventListener('scroll', () => {
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            //当点击的tab有子tab时做滚动逻辑
            if (this.clickTabFlag && arr.find(x => x === this.clickId)) {
                this.childTabClass = '' //无子tab时清空tab的类名
                return
            }

            if (!$idsTop[$idsTop.length - 1]) {
                $idsTop = arr.map(item => {
                    let itemTop
                    let arr
                    if (item instanceof Array) {
                        const prevHeight = document.getElementById(
                            item[0]
                        ).offsetHeight //因这里一个选项有两个表格，需获取前一个表格的高度进行计算
                        arr = item.map((x, i) => {
                            if (i === 0) {
                                return document.getElementById(x).offsetTop
                            } else {
                                return (
                                    document.getElementById(x).offsetTop +
                                    prevHeight +
                                    document.getElementById(item[0]).offsetTop
                                )
                            }
                        })
                        return arr
                    } else {
                        itemTop = document.getElementById(item).offsetTop
                        return itemTop
                    }
                })
            }
            const scrollTop =
                document.documentElement.scrollTop || document.body.scrollTop
            // 倒序查找
            let curLocal = 0
            let curLocalChild = 1
            for (let len = $idsTop.length, i = len - 1; i >= 0; i--) {
                if ($idsTop[i] instanceof Array) {
                    let item = $idsTop[i]
                    for (let lenth = item.length, j = lenth - 1; j >= 1; j--) {
                        let itemChild = $idsTop[i][j]
                        if (scrollTop + 1 >= itemChild) {
                            curLocalChild = j
                            break
                        }
                    }
                    if (scrollTop + 1 >= item[0]) {
                        curLocal = i
                        break
                    }
                } else {
                    let item = $idsTop[i]
                    if (scrollTop + 1 >= item) {
                        curLocal = i
                        break
                    }
                }
            }
            // 设置对应tabName
            if (arr[curLocal] instanceof Array) {
                this.tabsName = arr[curLocal][0]
                this.tabsNameChild = arr[curLocal][curLocalChild]
            } else {
                this.tabsName = arr[curLocal]
            }
            //动态改变二级选项卡类名
            arr.forEach((item, index) => {
                if (item instanceof Array) {
                    let tabNavHeight = document.querySelector(
                        '.childTab .el-tabs__nav'
                    )
                        ? document.querySelector('.childTab .el-tabs__nav')
                            .offsetHeight
                        : 0
                    if (scrollTop + 1 >= $idsTop[index + 1] - tabNavHeight) {
                        this.childTabClass = 'childTab2'
                    } else if (scrollTop <= $idsTop[index][1]) {
                        this.childTabClass = ''
                    } else {
                        this.childTabClass = 'childTab1'
                    }
                }
            })
        })

        this.screenWidth = document.documentElement.clientWidth - this.topHeight
        this.screenHeight = document.documentElement.clientHeight - this.topHeight
        window.addEventListener('resize', () => {
            this.screenWidth = document.documentElement.clientWidth - this.topHeight
            this.screenHeight = document.documentElement.clientHeight - this.topHeight
            $idsTop = arr.map(item => {
                let itemTop
                let arr
                if (item instanceof Array) {
                    const prevHeight = document.getElementById(
                        item[0]
                    ).offsetHeight //因这里一个选项有两个表格，需获取前一个表格的高度进行计算
                    arr = item.map((x, i) => {
                        if (i === 0) {
                            return document.getElementById(x).offsetTop
                        } else {
                            return (
                                document.getElementById(x).offsetTop +
                                prevHeight +
                                document.getElementById(item[0]).offsetTop
                            )
                        }
                    })
                    return arr
                } else {
                    itemTop = document.getElementById(item).offsetTop
                    return itemTop
                }
            })
        })

        this.scorllDtl()
    }
}
</script>

<style lang="scss" scoped>
.buttons {
    left: 0;
}

.e-form {
    margin-bottom: 80px;
    padding: 0 20px;

    .tabs-title::before {
        content: '';
        height: 22px;
        width: 8px;
        border-radius: 40px;
        background-color: #2e61d7;
        display: block;
        position: absolute;
        left: 20px;
        margin-right: 20px;
    }
}

.e-table {
    background: #fff;
}

::v-deep.el-table .warning-row {
    display: none;
}

// ::v-deep.el-table__body-wrapper::-webkit-scrollbar{
//      width: 6px !important; // 横向滚动条
//     height: 10px !important// 纵向滚动条
// }

::v-deep .el-table__body-wrapper::-webkit-scrollbar {
    width: 6px; // 横向滚动条
    height: 10px; // 纵向滚动条
}

// 滚动条的滑块
::v-deep .el-table__body-wrapper::-webkit-scrollbar-thumb {
    background-color: #ddd;
    border-radius: 5px;
}

.el-tab-pane {
    margin-left: -10px;
}

.childTab {
    ::v-deep .el-tabs__header {
        position: absolute !important;
    }

    ::v-deep .el-tabs__content {
        padding: 0 0 0 20px !important;
    }
}

.childTab1 {
    ::v-deep .el-tabs__header {
        position: absolute !important;

        .el-tabs__nav-scroll {
            position: relative;

            .el-tabs__nav {
                position: fixed;
                top: 0;
                width: 190px;
            }
        }
    }
}

.childTab2 {
    ::v-deep .el-tabs__header {
        position: absolute !important;

        .el-tabs__nav-scroll {
            position: relative;

            .el-tabs__nav {
                position: absolute;
                bottom: 0;
                width: 100%;
            }
        }
    }
}
</style>
